package com.yzf.enterprise.framework.config;

import org.springframework.util.StringUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @author shadowyy
 * @version 2020/4/21 03:06
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    private final String requestBody;

    HttpServletRequest httpServletRequest;

    private Cookie[] cookies;

    public RequestWrapper(HttpServletRequest httpServletRequest, String requestBody) throws IOException {
        super(httpServletRequest);
        this.requestBody = requestBody;
        this.httpServletRequest = httpServletRequest;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new StringReader(requestBody));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            private final InputStream in = new ByteArrayInputStream(requestBody.getBytes(
                    StringUtils.isEmpty(httpServletRequest.getCharacterEncoding()) ? "UTF-8" : httpServletRequest.getCharacterEncoding()));

            @Override
            public int read() throws IOException {
                return in.read();
            }
        };
    }

    @Override
    public Cookie[] getCookies() {
        return cookies;
    }

    public void setCookies(Cookie[] cookies) {
        this.cookies = cookies;
    }

}
